<template>
  <div class='uploader-container'>
    <van-cell
      class='van-sku-messages__image-cell'
      slot='default'
      :title='cellTitle'
      :label='cellLabel'
    >
      <!-- slot -->
      <template>
        <div class='van-sku-messages__image-cell-value'>
          <van-uploader
            :class='uploadCount'
            v-model='goodsimgList'
            accept='image/*'
            multiple
            :max-size='3145728'
            :max-count='uploadCount'
            :preview-size='previewImgSize'
            capture='camera'
            :after-read='onAfterRead'
            :before-read='onBeforeRead'
          />
        </div>
      </template>
    </van-cell>
  </div>
</template>
<script>
import Vue from 'vue'
import { Uploader, Cell } from 'vant'
Vue.use(Uploader).use(Cell)

export default {
  data () {
    return {
      goodsimgList: []
      // 不需要v-model='goodsimgList'(还是要: 如果一张一张的传file最后只有一个)
      // upload-text='上传'
    }
  },
  props: {
    cellTitle: { type: String, default: 'XXX' },
    cellLabel: { type: String, default: '' },
    uploadCount: { type: Number, default: 2 },
    previewImgSize: { type: String, default: '.8rem' }
  },
  methods: {
    onAfterRead (file) {
      // 此时可以自行将文件上传至服务器
      // 自定义事件
      // console.log('file', file);
      this.$emit('getfilelist', this.goodsimgList)
    },
    onBeforeRead (file) {
      // 上传校验: 返回布尔值
      if (file.type !== 'image/jpeg') {
        this.$toast({
          message: '请上传 jpg 格式图片',
          duration: 500, // 默认毫秒
          position: 'bottom'
        })
        return false
      }

      if (file.size >= 3145728) {
        this.$toast({
          message: '单张图片大小不能超过3M',
          duration: 500, // 默认毫秒
          position: 'bottom'
        })
        return false
      }
      return true
    }
  }
}
</script>
